<template>
  <AppModal v-model:visible="modalVisible" :title="modalTitle" width="1200px">
    <div class="flaw-count-detail">
      <div class="detail-header">
        <div class="segment-info">
          <div class="segment-range">
            路段范围：{{ segment?.start }}米 - {{ segment?.end }}米 
            ({{ segment ? segment.end - segment.start : 0 }}米)
          </div>
          <div class="flaw-count">
            缺陷总数：<el-tag type="primary">{{ segment?.flawCount || 0 }}个</el-tag>
          </div>
        </div>
        <div class="time-range">
          时间范围：{{ formatDateTime(startTime) }} - {{ formatDateTime(endTime) }}
        </div>
      </div>

      <!-- 筛选区域 -->
      <div class="filter-section">
        <div class="filter-item">
          <label>缺陷类型：</label>
          <el-select v-model="filterParams.flawType" placeholder="选择缺陷类型" clearable @change="handleFilter">
            <el-option label="全部" value="" />
            <el-option label="裂缝" value="裂缝" />
            <el-option label="渗水" value="渗水" />
            <el-option label="钢筋锈蚀" value="钢筋锈蚀" />
            <el-option label="混凝土剥落" value="混凝土剥落" />
            <el-option label="其他" value="其他" />
          </el-select>
        </div>
        <div class="filter-item">
          <label>严重程度：</label>
          <el-select v-model="filterParams.level" placeholder="选择严重程度" clearable @change="handleFilter">
            <el-option label="全部" value="" />
            <el-option label="轻微" value="轻微" />
            <el-option label="一般" value="一般" />
            <el-option label="严重" value="严重" />
            <el-option label="紧急" value="紧急" />
          </el-select>
        </div>
        <div class="filter-item">
          <label>处理状态：</label>
          <el-select v-model="filterParams.status" placeholder="选择处理状态" clearable @change="handleFilter">
            <el-option label="全部" value="" />
            <el-option label="待确认" value="待确认" />
            <el-option label="待处理" value="待处理" />
            <el-option label="已处理" value="已处理" />
          </el-select>
        </div>
        <div class="filter-item">
          <label>关键词：</label>
          <el-input 
            v-model="filterParams.keyword" 
            placeholder="搜索缺陷描述" 
            style="width: 200px"
            @input="debounceFilter"
            clearable
          />
        </div>
        <el-button type="primary" @click="handleFilter">查询</el-button>
        <el-button @click="handleResetFilter">重置</el-button>
      </div>

      <el-table 
        v-loading="loading" 
        :data="flawList" 
        stripe 
        style="width: 100%"
        height="400"
      >
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="flawType" label="缺陷类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getFlawTypeTagType(row.flawType)">
              {{ row.flawType }}
            </el-tag>
          </template>
        </el-table-column>
                 <el-table-column prop="flawDistance" label="具体位置(米)" width="110" />
         <el-table-column prop="flawDesc" label="缺陷描述" show-overflow-tooltip min-width="200" />
         <el-table-column prop="level" label="严重程度" width="100">
           <template #default="{ row }">
             <el-tag :type="getSeverityTagType(row.level)">
               {{ row.level }}
             </el-tag>
           </template>
         </el-table-column>
         <el-table-column label="处理状态" width="100">
           <template #default="{ row }">
             <el-tag :type="getStatusTagType(getFlawStatus(row))">
               {{ getFlawStatus(row) }}
             </el-tag>
           </template>
         </el-table-column>
         <el-table-column prop="createTime" label="发现时间" width="160">
           <template #default="{ row }">
             {{ formatDateTime(row.createTime) }}
           </template>
         </el-table-column>
        <el-table-column label="操作" width="80" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleViewImage(row)">
              查看图片
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-if="total > 0"
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        background
        class="pagination"
        @size-change="getFlawList"
        @current-change="getFlawList"
      />
    </div>

    <!-- 图片查看器 -->
    <el-image-viewer
      v-if="imageViewerVisible"
      :url-list="currentImages"
      @close="imageViewerVisible = false"
    />
  </AppModal>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue';
import { ElTable, ElTableColumn, ElTag, ElPagination, ElButton, ElSelect, ElOption, ElInput, ElImageViewer } from 'element-plus';
import { formatDateTime } from '@/utils';
import { getFlawsByTime } from '@/api/flaws';
import AppModal from '@/components/common/AppModal.vue';

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  segment: {
    type: Object,
    default: null
  },
  startTime: {
    type: String,
    default: ''
  },
  endTime: {
    type: String,
    default: ''
  }
});

// Emits
const emit = defineEmits(['update:visible']);

// 响应式数据
const loading = ref(false);
const flawList = ref([]);
const total = ref(0);
const imageViewerVisible = ref(false);
const currentImages = ref([]);

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10
});

const filterParams = reactive({
  flawType: '',
  level: '',
  status: '',
  keyword: ''
});

// 防抖定时器
let debounceTimer = null;

// 计算属性
const modalVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
});

const modalTitle = computed(() => {
  if (!props.segment) return '路段缺陷详情';
  return `路段缺陷详情 (${props.segment.start}m - ${props.segment.end}m)`;
});

// 获取缺陷类型标签类型
const getFlawTypeTagType = (flawType) => {
  const typeMap = {
    '裂缝': 'danger',
    '渗水': 'primary',
    '钢筋锈蚀': 'warning',
    '混凝土剥落': 'info',
    '其他': ''
  };
  return typeMap[flawType] || '';
};

// 获取严重程度标签类型
const getSeverityTagType = (severity) => {
  const typeMap = {
    '轻微': 'info',
    '一般': 'warning', 
    '严重': 'danger',
    '紧急': 'danger'
  };
  return typeMap[severity] || 'info';
};

// 根据confirmed和uploaded字段计算缺陷处理状态
const getFlawStatus = (flaw) => {
  if (!flaw.confirmed) {
    return '待确认';
  } else if (flaw.confirmed && !flaw.uploaded) {
    return '待处理';
  } else if (flaw.confirmed && flaw.uploaded) {
    return '已处理';
  }
  return '未知';
};

// 获取状态标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    '待确认': 'warning',
    '待处理': 'danger',
    '已处理': 'success',
    '未知': 'info'
  };
  return typeMap[status] || 'info';
};

// 查看图片
const handleViewImage = (row) => {
  // 使用实际的图片URL，如果没有则使用占位图
  const images = [];
  if (row.flawImageUrl) {
    images.push(row.flawImageUrl);
  } else {
    // 使用占位图
    images.push(`https://picsum.photos/800/600?random=${row.id}`);
  }
  
  currentImages.value = images;
  imageViewerVisible.value = true;
};

// 获取缺陷列表
const getFlawList = async () => {
  if (!props.segment) return;
  
  loading.value = true;
  try {
    const response = await getFlawsByTime(props.startTime, props.endTime);
    
    if (response.data.code === '200' || response.data.code === 200) {
      let allFlaws = response.data.rows
      
      // 根据路段筛选
      allFlaws = allFlaws.filter(flaw => {
        const location = parseFloat(flaw.flawDistance) || 0;
        return location >= props.segment.start && location < props.segment.end;
      });
      
      // 根据筛选条件进一步筛选
      if (filterParams.flawType) {
        allFlaws = allFlaws.filter(flaw => flaw.flawType === filterParams.flawType);
      }
      if (filterParams.level) {
        allFlaws = allFlaws.filter(flaw => flaw.level === filterParams.level);
      }
      if (filterParams.status) {
        allFlaws = allFlaws.filter(flaw => getFlawStatus(flaw) === filterParams.status);
      }
      if (filterParams.keyword) {
        allFlaws = allFlaws.filter(flaw => 
          (flaw.flawName && flaw.flawName.includes(filterParams.keyword)) ||
          (flaw.flawDesc && flaw.flawDesc.includes(filterParams.keyword))
        );
      }
      
      // 前端分页
      const start = (queryParams.pageNum - 1) * queryParams.pageSize;
      const end = start + queryParams.pageSize;
      
      flawList.value = allFlaws.slice(start, end);
      total.value = allFlaws.length;
    } else {
      throw new Error(response.msg || '获取数据失败');
    }
    
  } catch (error) {
    console.error('获取缺陷列表失败:', error);
    flawList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 筛选处理
const handleFilter = () => {
  queryParams.pageNum = 1;
  getFlawList();
};

// 防抖筛选
const debounceFilter = () => {
  if (debounceTimer) {
    clearTimeout(debounceTimer);
  }
  debounceTimer = setTimeout(() => {
    handleFilter();
  }, 500);
};

// 重置筛选
const handleResetFilter = () => {
  filterParams.flawType = '';
  filterParams.level = '';
  filterParams.status = '';
  filterParams.keyword = '';
  queryParams.pageNum = 1;
  getFlawList();
};

// 监听 visible 变化
watch(() => props.visible, (newVal) => {
  if (newVal) {
    // 重置筛选和分页
    handleResetFilter();
  }
});

// 监听路段变化
watch(() => props.segment, () => {
  if (props.visible && props.segment) {
    handleResetFilter();
  }
});
</script>

<style lang="scss" scoped>
@use '../../assets/scss/variables' as *;

.flaw-count-detail {
  .detail-header {
    margin-bottom: 20px;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 8px;
    
    .segment-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
      
      .segment-range,
      .flaw-count {
        font-size: 14px;
        color: $text-color-regular;
        font-weight: 500;
      }
    }
    
    .time-range {
      font-size: 12px;
      color: $text-color-placeholder;
    }
  }
  
  .filter-section {
    display: flex;
    align-items: center;
    gap: 15px;
    margin-bottom: 20px;
    padding: 15px;
    background: #fff;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    flex-wrap: wrap;
    
    .filter-item {
      display: flex;
      align-items: center;
      gap: 8px;
      
      label {
        white-space: nowrap;
        font-size: 14px;
        color: $text-color-regular;
      }
      
      .el-select {
        width: 150px;
      }
    }
  }
  
  .pagination {
    margin-top: 20px;
    justify-content: center;
  }
}
</style> 